package com.gjintel.framework.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

public class ValidateLoginFilter implements Filter {
	private static final Logger LOG = Logger.getLogger(ValidateLoginFilter.class);
	private String[] unFilterURLs;

	@Override
	public void init(FilterConfig config) throws ServletException {
		String urls = config.getInitParameter("unFilterURLs");
		if (urls != null) {
			unFilterURLs = urls.split(",");
		}
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hreq = (HttpServletRequest) req;
		String url = hreq.getRequestURI();
		if(!url.endsWith("/")){
			HttpServletResponse hres = (HttpServletResponse) res;
			HttpSession session = hreq.getSession();
			Object obj = session.getAttribute("loginUser");
			// 如果是在配置中不需要拦截的情况下的进行放行
			for (String unUrl : unFilterURLs) {
				if (unUrl.endsWith("/*")) {
					unUrl = hreq.getContextPath() + unUrl.replace("/*", "");
					if (url.startsWith(unUrl)) {
						chain.doFilter(req, res);
						return;
					}
				} else if (url.startsWith(hreq.getContextPath() + unUrl)) {
					chain.doFilter(req, res);
					return;
				}
			}
			if (obj == null && !url.contains(".")) {
				this.writeJsonData(hres);
				return;
			}
		}
		// 对页面功能的控制实现
//		if (obj != null) {
//			this.pageFunctionParams(hreq);
//		}
		chain.doFilter(req, res);
	}
	
	/**
	 * @description 返回未登陆的数据到客户端
	 * @author fengya
	 * @date 2015-9-16 下午02:31:29
	 * @param hres
	 * @return void
	 */
	private void writeJsonData(HttpServletResponse hres) {
		PrintWriter pw = null;
		try {
			hres.setContentType("text/html;charset=utf-8");
			hres.setHeader("Pragma", "No-cache");
			hres.setHeader("Cache-Control", "no-cache");
			hres.setDateHeader("Expires", 0);
			pw = hres.getWriter();
			pw.write("unLogin");
			pw.flush();
		} catch (Exception e) {
			LOG.debug("输出流出现异常！",e);
		} finally {
			if (pw != null) {
				pw.close();
			}
		}
	}
}
